package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.SubAreaService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage(value = "json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class SubAreaAction extends BaseAction<SubArea> {

	@Autowired
	private SubAreaService subAreaService;

	// 接收上传文件
	private File file;

	public void setFile(File file) {
		this.file = file;
	}

	@Action(value = "subArea_inportSubArea")
	public String importSubArea() throws Exception {
		// 定义集合存储读取execl文件中的分区数据
		List<SubArea> subAreas = new ArrayList<SubArea>();
		// 解析execl文件
		// 1.加载execl文件对象
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 2.读取一个sheet
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
		// 3.读取sheet中每一行的数据
		for (Row row : sheet) {
			// 跳过第一行表头
			if (row.getRowNum() == 0) {
				continue;
			}
			// 如果此行的id为空，要求此行作废
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			// 将读取的数据封装到subarea对象中
			SubArea subArea = new SubArea();
			// 分区编号
			subArea.setId(row.getCell(0).getStringCellValue());
			// 定区编号,subArea中定义了多对一，分区维护外键,所以只需建立分区与定区的关联即可生成外键
			FixedArea fixedArea = new FixedArea();
			fixedArea.setId(row.getCell(1).getStringCellValue());
			subArea.setFixedArea(fixedArea);// 关联分区和定区，在表中生成外键
			// 区域编码
			Area area = new Area();
			area.setId(row.getCell(2).getStringCellValue());
			subArea.setArea(area);// 多对一，关联分区与区域，生成外键
			// 关键字
			subArea.setKeyWords(row.getCell(3).getStringCellValue());
			// 初始化
			subArea.setStartNum(row.getCell(4).getStringCellValue());
			// 结束号
			subArea.setEndNum(row.getCell(5).getStringCellValue());
			// 单双号
			subArea.setSingle(row.getCell(6).getStringCellValue().toCharArray()[0]);
			// 辅助关键字
			subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());

			subAreas.add(subArea);

		}
		// 调用业务层
		subAreaService.saveSubArea(subAreas);
		return NONE;
	}

	// 条件查询分区信息
	@Action(value = "subArea_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		Pageable pageable = new PageRequest(page - 1, rows);
		Specification<SubArea> specification = new Specification<SubArea>() {

			Predicate predicate = null;
			List<Predicate> list = new ArrayList<Predicate>();

			@Override
			public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 多表查询
				Join<SubArea, Area> joinArea = root.join("area", JoinType.INNER);
				// 省
				if (model.getArea() != null && StringUtils.isNotBlank(model.getArea().getProvince())) {
					Predicate p = cb.like(joinArea.get("province").as(String.class),
							"%" + model.getArea().getProvince() + "%");
					list.add(p);
				}
				// 市
				if (model.getArea() != null && StringUtils.isNotBlank(model.getArea().getCity())) {
					Predicate p = cb.like(joinArea.get("city").as(String.class), "%" + model.getArea().getCity() + "%");
					list.add(p);
				}
				// 区县
				if (model.getArea() != null && StringUtils.isNotBlank(model.getArea().getDistrict())) {
					Predicate p = cb.like(joinArea.get("district").as(String.class),
							"%" + model.getArea().getDistrict() + "%");
					list.add(p);
				}

				// 定区编码
				// 多表查询
				Join<SubArea, FixedArea> joinFixedArea = root.join("fixedArea", JoinType.INNER);

				if (model.getFixedArea() != null && StringUtils.isNotBlank(model.getFixedArea().getId())) {
					Predicate p = cb.equal(joinFixedArea.get("id").as(String.class), model.getFixedArea().getId());
					list.add(p);
				}
				// 关键字
				if (StringUtils.isNotBlank(model.getKeyWords())) {
					Predicate p = cb.like(root.get("keyWords").as(String.class), "%" + model.getKeyWords() + "%");
					list.add(p);
				}

				if (list != null && list.size() > 0) {
					Predicate[] pArr = new Predicate[list.size()];
					predicate = cb.and(list.toArray(pArr));
				}

				return predicate;
			}
		};
		Page<SubArea> pageDate = subAreaService.pageQueryCondition(specification, pageable);
		pushPageDataToValueStack(pageDate);
		return SUCCESS;
	}

	// 无条件分页查询
	@Action(value = "subArea_findAll", results = { @Result(name = "success", type = "json") })
	public String findAll() {
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<SubArea> page = subAreaService.findAll(pageable);
		pushPageDataToValueStack(page);
		return SUCCESS;
	}

	// 根据定区id查询已关联的分区
	private String fixedAreaId;

	public void setFixedAreaId(String fixedAreaId) {
		this.fixedAreaId = fixedAreaId;
	}

	@Action(value = "subArea_findAssociationSubArea", results = { @Result(name = "success", type = "json") })
	public String findAssociationSubArea() {
		List<SubArea> list = subAreaService.findAssociationSubArea(fixedAreaId);
		ServletActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}

}
